﻿using NLog;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Markup;

namespace playwrightJu3.Core
{
    public static class Checkers
    {
        private static Logger logger = LogManager.GetCurrentClassLogger();

        public static bool IsValidFileName(string name)
        {
            // 检查项目名称是否为空
            if (string.IsNullOrWhiteSpace(name))
            {
                logger.Warn("Invalid File Name|User is trying to create a project or file with an empty name.");
                return false;
            }
            if (name.StartsWith(' ') || name.EndsWith(' '))
            {
                logger.Warn("Invalid File Name|User is trying to create a project or file with a name that starts or ends with a space.");
                return false;
            }
            // 检查项目名称是否包含非法字符
            char[] invalidChars = Path.GetInvalidFileNameChars();
            if (name.IndexOfAny(invalidChars) >= 0)
            {
                logger.Warn("Invalid File Name|User is trying to create a project or file with a name that contains invalid characters.");
                return false;
            }
            return true;
        }

        public static bool IsFolderEmpty(string folderPath)
        {
            // 获取文件夹中的所有文件和子目录
            var files = Directory.GetFiles(folderPath);
            var directories = Directory.GetDirectories(folderPath);
            // 如果没有文件和子目录，则认为文件夹为空
            return files.Length == 0 && directories.Length == 0;
        }

        public static bool IsFolderExists(string folderPath)
        {
            // 检查文件夹是否存在
            return Directory.Exists(folderPath);
        }

        public static bool IsValidJuFile(string filePath)
        {
            try
            {
                string xaml = System.IO.File.ReadAllText(filePath, Encoding.UTF8);
                using var stringReader = new StringReader(xaml);
                using (var xmlReader = System.Xml.XmlReader.Create(stringReader))
                {
                    var obj = XamlReader.Load(xmlReader);

                }
                return true;
            }
            catch (XamlParseException e)
            {
                logger.Warn(e,"Invalid File|User is trying to open an invalid .ju file: " + filePath);
                return false;
            }
        }
    }
}
